import ast
import os
from datetime import datetime, timedelta, date
from docx import Document
import io
from pypdf import PdfReader
from typing import Union

from dotenv import load_dotenv
load_dotenv()


def get_week_start_end(date: datetime = None) -> tuple[datetime, datetime]:
    """
    获取指定日期所在周的开始和结束时间

    Args:
        date: 指定日期，默认为当前日期

    Returns:
        tuple: (周开始时间, 周结束时间)
    """
    if date is None:
        date = datetime.now()

    # 获取周一的日期 (weekday() 返回0-6，0为周一)
    week_start = date - timedelta(days=date.weekday())
    week_start = week_start.replace(hour=0, minute=0, second=0, microsecond=0)

    # 获取周日的日期
    week_end = week_start + timedelta(days=6, hours=23, minutes=59, seconds=59)

    return week_start, week_end


def format_datetime_to_date_string(time_value: Union[datetime, date, str]) -> str:
    """
    将时间值格式化为日期字符串，如果是datetime类型则精确到天

    Args:
        time_value: 时间值，可以是datetime、date或str类型

    Returns:
        str: 格式化后的日期字符串 (YYYY-MM-DD)
    """
    if isinstance(time_value, datetime):
        return time_value.strftime("%Y-%m-%d")
    elif isinstance(time_value, date):
        return time_value.strftime("%Y-%m-%d")
    else:
        return str(time_value)


def extract_text_content(file_bytes, filename, file_type):
    """
    根据文件类型提取文本内容
    """
    filename_lower = filename.lower()

    try:
        if filename_lower.endswith(".txt") or file_type == "text/plain":
            # 处理文本文件
            return file_bytes.decode("utf-8", errors="ignore")

        elif (
            filename_lower.endswith(".docx")
            or file_type
            == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        ):
            # 处理 docx 文件
            doc_stream = io.BytesIO(file_bytes)
            doc = Document(doc_stream)
            text_content = []

            # 提取段落文本
            for paragraph in doc.paragraphs:
                if paragraph.text.strip():
                    text_content.append(paragraph.text.strip())

            # 提取表格内容
            for table in doc.tables:
                table_text = []
                for row in table.rows:
                    row_text = []
                    for cell in row.cells:
                        cell_text = cell.text.strip()
                        if cell_text:
                            row_text.append(cell_text)
                    if row_text:
                        table_text.append(" | ".join(row_text))

                if table_text:
                    text_content.append("\n".join(table_text))

            return "\n".join(text_content)

        elif filename_lower.endswith(".pdf") or file_type == "application/pdf":
            # 处理 PDF 文件
            pdf_stream = io.BytesIO(file_bytes)
            pdf_reader = PdfReader(pdf_stream)
            text_content = []
            for page in pdf_reader.pages:
                page_text = page.extract_text()
                if page_text.strip():
                    text_content.append(page_text.strip())
            return "\n".join(text_content)

        else:
            # 尝试按文本解析
            try:
                return file_bytes.decode("utf-8", errors="ignore")
            except:
                return f"无法解析文件内容: {filename}"

    except Exception as e:
        print(f"提取文本内容失败 {filename}: {str(e)}")
        return f"文件内容提取失败: {filename}"


def parse_string_to_list(string_value: str) -> list:
    """
    将字符串形式的数组安全地解析为Python列表

    Args:
        string_value: 字符串形式的数组，例如 "['1dd57f2470c364622e2a788dd61ca671']"

    Returns:
        list: 解析后的列表，解析失败时返回空列表

    Examples:
        >>> parse_string_to_list("['a', 'b', 'c']")
        ['a', 'b', 'c']
        >>> parse_string_to_list("[]")
        []
        >>> parse_string_to_list("invalid")
        []
    """
    if not string_value or not string_value.strip():
        return []

    try:
        # 使用 ast.literal_eval 安全地解析字符串
        parsed_list = ast.literal_eval(string_value.strip())

        # 确保返回的是列表类型
        if isinstance(parsed_list, list):
            return parsed_list
        else:
            # 如果不是列表，尝试将其转换为列表
            return [parsed_list]

    except (ValueError, SyntaxError) as e:
        print(f"解析字符串数组失败: {string_value}, 错误: {e}")
        return []


